/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import SelectionExtensionAbility from '@ohos.selectionInput.SelectionExtensionAbility'
import { rpc } from '@kit.IPCKit';
import Want from '@ohos.app.ability.Want';
import selectionManager from '@ohos.selectionInput.selectionManager';
import type { PanelInfo } from '@ohos.selectionInput.SelectionPanel';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { SelectionModel } from '../models/SelectionModel';


class SelectionAbilityStub extends rpc.RemoteObject {
  constructor(des) {
    if (typeof des === 'string') {
      super(des);
    } else {
      return null;
    }
  }
  onRemoteMessageRequest(
    code: number,
    data: rpc.MessageSequence,
    reply: rpc.MessageSequence,
    options: rpc.MessageOption
  ): boolean | Promise<boolean> {
    hilog.info(0, 'SelectionExtensionAbility', `enter onRemoteMessageRequest code: ${code}`);
    try{
      switch (code) {
        case 16:
          reply.writeString("Hello XYING6");
          return true;
      }
    } catch (error) {
      hilog.info(0, 'SelectionExtensionAbility', `sendDisconnect sendMessageRequest failed:${error}`);
    };
  }
}

class ServiceExtAbility extends SelectionExtensionAbility {
  panel_: selectionManager.Panel = undefined;
  sleep: (ms: number) => Promise<Function> = (ms: number): Promise<Function> => {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  onConnect(want: Want): rpc.RemoteObject {
    hilog.info(0x0000, 'SelectionExtensionAbility', 'onConnect, want:' + want.abilityName);
    let panelInfo: PanelInfo = {
      panelType: 1,
      x: 0,
      y: 0,
      width: 1000,
      height: 500
    }
    hilog.info(0x0000, 'SelectionExtensionAbility', "[XYING6] 1: " + this.context?.constructor?.name);
    selectionManager.createPanel(this.context, panelInfo)
      .then(async (panel: selectionManager.Panel) => {
        hilog.info(0x0000, 'SelectionExtensionAbility', '-----------2');
        this.panel_ = panel;
        SelectionModel.getInstance().setSelectionPanel(panel);
        panel.setUiContent('pages/Index')
          .catch((error: BusinessError) => {
            hilog.info(0x0000, 'SelectionExtensionAbility', `Failed to setUiContent: [${JSON.stringify(error)}]`);
            return;
          });
        hilog.info(0x0000, 'SelectionExtensionAbility', 'Succeed in creating panel.');

        selectionManager.on('selectionCompleted', (info: selectionManager.SelectionInfo) => {
          this.onSelected(info);
        });
      })
      .catch((error: BusinessError) => {
        hilog.info(0x0000, 'SelectionExtensionAbility', `Failed to createPanel: ${JSON.stringify(error)}`);
        return;
      });

    return new SelectionAbilityStub('remote');
  }

  async onSelected(info: selectionManager.SelectionInfo) {
    hilog.info(0x0000, 'SelectionExtensionAbility', '-----------on');
    hilog.info(0x0000, 'SelectionExtensionAbility', 'SelectionInfo text：%{public}s', info.text);
    SelectionModel.getInstance().setMessage(info.text);
    this.panel_.moveTo(info.startDisplayX, info.startDisplayY);
    await this.panel_.show();
    hilog.info(0x0000, 'SelectionExtensionAbility', `show panel end`);
    this.panel_.on('hidden', () => {
      hilog.info(0x0000, 'SelectionExtensionAbility', 'panel has hidden');
    })
    this.panel_.on('destroyed', () => {
      hilog.info(0x0000, 'SelectionExtensionAbility', 'panel has destroyed');
    })
    await this.sleep(10 * 1000);
    await this.sleep(10 * 1000);
    // this.panel_.startMoving();
    await this.sleep(10 * 1000);
    try {
      await this.panel_.hide()
      // .catch((error: Error) => {
      //   hilog.info(0x0000, 'SelectionExtensionAbility', `Failed to hide: ${JSON.stringify(error)}`);
      //   return;
      // });
    } catch (error) {
      hilog.info(0x0000, 'SelectionExtensionAbility', `Failed to hide: ${JSON.stringify(error)}`);
    }
    await this.sleep(10 * 1000);
    await this.panel_.show();
  }

  onDisconnect(): void {
    hilog.info(0x0000, 'SelectionExtensionAbility', 'onDisconnect');
    selectionManager.destroyPanel(this.panel_);
  }

  onDestroy(): void {
    hilog.info(0x0000, 'SelectionExtensionAbility', 'onDestroy');
  }
}

export default ServiceExtAbility;